<template>
  <div id="map-container"></div>
</template>

<script setup lang="ts">
  import {
    onMounted,
    onUnmounted,
    withDefaults,
    defineProps,
    watch,
  } from 'vue';
  import AMapLoader from '@amap/amap-jsapi-loader';

  interface Position {
    position: [number, number];
    text: string;
  }

  interface Props {
    positionList?: Position[];
  }
  const props = withDefaults(defineProps<Props>(), {
    positionList: () => {
      return [];
    },
  });

  let map: any = null;
  let AMap: any = null;
  const defaultCenter: number[] = [116.406315, 39.908775];
  const markers: any[] = [];

  // 实例化点标记
  const addMarker = (positionArr?: Position[]) => {
    if (!map) {
      map = new AMap.Map('map-container', {
        resizeEnable: true,
        center: defaultCenter,
        zoom: 13,
      });
    }

    if (markers.length) {
      map.remove(markers);
    }
    if (positionArr?.length) {
      positionArr.forEach((t) => {
        const markerContent = `<div style="position: relative;width:25px;height: 34px">
             <img style="width: 100%;height: 100%" src="//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png">
             <div style="position:absolute;left: 30px;top: 5px;background:#fff;width: 83px; padding: 3px; box-shadow: 0px 0px 5px rgba(10, 10, 10, 0.7);">${t.text}</div>
          </div>`;
        const mark = new AMap.Marker({
          map,
          content: markerContent,
          icon:
            '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
          position: t.position,
          direction: 'right',
          offset: new AMap.Pixel(10, 0), // 设置文本标注偏移量
        });
        markers.push(mark);
      });
      map.setFitView(null, false, [150, 60, 100, 60]);
    }
  };

  watch(
    () => props.positionList,
    (newVal) => {
      if (AMap) {
        addMarker(newVal);
      }
    }
  );

  onMounted(() => {
    AMapLoader.load({
      key: process.env.MAP_KEY as string, // 申请好的Web端开发者Key，首次调用 load 时必填
      version: '1.4.4', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ['AMap.moveAnimation'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
      .then((res) => {
        AMap = res;
        addMarker(props.positionList);
      })
      .catch((e) => {
        console.log(e);
      });
  });

  onUnmounted(() => {
    map?.destroy();
  });
</script>

<style lang="less">
  #map-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
</style>
